package main

import (
	"flag"
	"fmt"
	"gm/message"
	"log"
	"os"
	"path/filepath"
	"strings"
)

var (
	users          string
	content        string
	subject        string
	h              bool
	t              string
	late           int64  //延迟发送时间
	attachFilePath string // 附件路径
	attachFileName string //附件名
	sendInOne      bool   //是有使用一封邮件发送给所有用户，还是单独每个用户发一封
)

func init() {
	flag.BoolVar(&h, "h", false, "gm help")
	flag.StringVar(&content, "c", "", "the message `content`")
	flag.StringVar(&subject, "s", "", "the message `subject`")
	flag.StringVar(&users, "u", "", "the `users` who to send, use , to seperate user")
	flag.StringVar(&t, "t", "email", "the message `type`: email, sms")
	flag.Int64Var(&late, "l", 0, "the time(millisecond) `late` to send")
	flag.StringVar(&attachFilePath, "ap", "", "the attach file path, use , to seperate file")
	flag.StringVar(&attachFileName, "an", "", "the attach file name, use , to seperate name")
	flag.BoolVar(&sendInOne, "so", true, "send all users in one email, default is true")
}

/*
go run main.go -u xxx@qq.com,xxx@qq.com -c "hello, just for gm test" -s gm -t email
*/
func main() {
	flag.Parse()
	if h {
		flag.Usage()
		return
	}

	if content == "" {
		log.Println("content can't be empty")
		return
	}
	if users == "" {
		log.Println("users can't be empty")
		return
	}
	if subject == "" {
		log.Println("subject can't be empty")
		return
	}

	var msg message.Message
	if t == "" || t == message.EmailType {
		msg = new(message.Email)
	} else if t == message.SMSType {
		msg = new(message.SMS)
	} else {
		log.Printf("wrong message type %s \n, pls use email or sms, default is email", t)
		return
	}
	var attachFilePaths []string
	var attachFileNames []string
	if attachFilePath != "" {
		attachFilePaths = strings.Split(attachFilePath, ",")
		for _, v := range attachFilePaths {
			attachFileNames = append(attachFileNames, filepath.Base(v))
		}
		if attachFileName != "" {
			fileNames := strings.Split(attachFileName, ",")
			plen := len(attachFilePaths)
			for i, v := range fileNames {
				if i >= plen {
					break
				}
				attachFileNames[i] = v
			}
		}
	}

	msg.Send(subject, content, users, attachFilePaths, attachFileNames, late, sendInOne)

}

func usage() {
	fmt.Fprintf(os.Stderr, `
	gm version: gm/1.0
	Usage: gm [-h help] [-u users] [-s subject] [-c content] [-t type]

	Options:
	`)
	flag.PrintDefaults()
}
